AI Script Assistant
The AI Script Assistant uses natural language descriptions of control logic or data processing workflows to automatically generate C# scripts that comply with syntax specifications. It also supports explanation, debugging, and optimization of existing scripts. Its core purpose is to rapidly complete script-based engineering development.
Feature Description
- Supports describing trigger conditions and operation steps (e.g., data reading, API calls, variable updates) for scripts via natural language; the AI automatically generates compliant C# scripts.
- Analyze uncommented or obscure engineering scripts line by line, generating clear functional descriptions to reduce the learning curve.
- Provides intelligent troubleshooting and optimization suggestions for script runtime errors (e.g., logic flaws, data parsing failures) or efficiency issues, reducing debugging time.
Core Advantages
1. Lowers the Programming Barrier
OT engineers without a professional programming background (e.g., process engineers, electrical engineers) can complete system integration and data processing script development without deeply learning C# syntax.
Traditional Approach vs. AI Approach:
Traditional Approach:
Learn C# syntax → Learn API documentation → Write code → Debug errors → Optimize performance
Requires: Programming ability + significant learning time
AI Approach:
Describe requirements → AI generates code → Test and verify → Fine-tune optimization
Requires: Ability to express logic clearly
2. Improves Script Quality and Efficiency
- Syntax Compliance: Generated scripts conform to industrial programming standards, reducing syntax errors.
- Exception Handling: Automatically adds necessary exception handling logic to improve script robustness.
- Performance Optimization: The optimization feature improves script execution efficiency and reduces system resource usage.
- Code Comments: Automatically adds clear comments for easier maintenance.
3. Accelerates Engineering Knowledge Transfer
Quickly explains the functionality of legacy scripts, helping new engineers or maintenance personnel get up to speed quickly and preventing knowledge loss due to personnel changes.
Scenario Example:
- Taking over an old project with hundreds of lines of uncommented code.
- Traditional approach: Read and understand line by line, potentially taking days.
- AI approach: Paste the code, generates a functional description, understand the core logic within 30 minutes.
Typical Scenarios
Scenario 1: Third-Party System Integration Script Development
Background: Production data needs to be reported to the MES system or production orders retrieved from the ERP.
Requirement Description:
When the work order ID changes, obtain MES data via API and write it to local variables.
Specific requirements:
- Monitored variable: Work Order ID
- API address: http://mes.company.com/api/getWorkOrder
- Request method: POST
- Request parameters: {"order Id": "Work Order ID value"}
- Returned data: {"productModel": "Product model", "targetQty": Target quantity}
- Write to variables: Product Model, Target Quantity
**AI-generated script: **
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
public class MESIntegration
{
private string lastWorkOrderID = "";
public void OnWorkOrderChanged(string currentWorkOrderID)
{
// Check if work order ID has changed
if (currentWorkOrderID != lastWorkOrderID && !string.IsNullOrEmpty(currentWorkOrderID))
{
lastWorkOrderID = currentWorkOrderID;
try
{
// Call MES API to get work order data
var workOrderData = GetWorkOrderFromMES(currentWorkOrderID);
// Write to local variables
CMS.SetVariable("ProductModel", workOrderData.ProductModel);
CMS.SetVariable("TargetQuantity", workOrderData.TargetQty);
CMS.Log($"Work order data retrieved successfully: {workOrderData.ProductModel}, Target quantity: {workOrderData.TargetQty}");
}
catch (Exception ex)
{
CMS.LogError($"Failed to get MES data: {ex.Message}");
}
}
}
private WorkOrderData GetWorkOrderFromMES(string orderId)
{
using (var client = new HttpClient())
{
// Set timeout
client.Timeout = TimeSpan.FromSeconds(10);
// Build request content
var requestData = new { orderId = orderId };
var jsonContent = JsonConvert.SerializeObject(requestData);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// Send POST request
var response = client.PostAsync("http://mes.company.com/api/getWorkOrder", content).Result;
response.EnsureSuccessStatusCode();
// Parse response data
var responseJson = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<WorkOrderData>(responseJson);
}
}
}
public class WorkOrderData
{
public string ProductModel { get; set; }
public int TargetQty { get; set; }
}
Value:
- No need to manually write complex HTTP request code.
- Automatically handles exceptions.
- Shortens system integration engineering cycles from days to hours.
Scenario 2: Maintaining Legacy Project Scripts
Background: Taking over an old project script without comments, needing to quickly understand its functionality.
Original Script (no comments):
public void Process()
{
var v1 = CMS.GetVariable("V001");
var v2 = CMS.GetVariable("V002");
if (v1 > 100 && v2 < 50)
{
CMS.SetVariable("V003", 1);
CMS.CallAPI("http://api/alarm", "POST", "{\"type\":\"high\"}");
}
else
{
CMS.SetVariable("V003", 0);
}
}
Ask the AI:
Please explain the functionality of this script.
AI Explanation:
This script performs monitoring and alarm handling:
1. Reads two variables:
- V001: monitored value such as temperature or pressure
- V002: another related parameter
2. Condition evaluation:
- When V001 is greater than 100 (exceeds threshold)
- AND V002 is less than 50 (below normal value)
- Trigger alarm only when both conditions are met
3. Alarm handling:
- Set V003 to 1 (alarm status flag)
- Call external API to send a high-level alarm notification
4. Normal state:
- When alarm conditions are not met, set V003 to 0 (normal state)
Suggestions:
- Use meaningful names for variables (e.g., Temperature, Pressure)
- Define thresholds 100 and 50 as constants for easier adjustment later
- Add exception handling to prevent API call failures from affecting the main flow
Value:
- Quickly understand legacy code logic.
- Reduce maintenance time.
- Receive optimization suggestions.
Scenario 3: Script Debugging and Optimization
Background: Script has runtime errors or low efficiency.
Problematic Script:
public void UpdateData()
{
for (int i = 0; i < 1000; i++)
{
var data = CMS.GetVariable("Sensor_" + i);
CMS.WriteToDatabase("INSERT INTO data VALUES (" + i + ", " + data + ")");
}
}
Ask the AI:
This code performs poorly. How can it be optimized?
AI Optimization Suggestions:
Problem analysis:
- Frequent database insert calls inside a loop, very poor performance.
- String concatenation method is unsafe and has SQL injection risk.
- No batch processing mechanism.
Optimized solution:
public void UpdateData()
{
// Use batch insert to improve performance
var dataList = new List<SensorData>();
// Collect all data first
for (int i = 0; i < 1000; i++)
{
var data = CMS.GetVariable($"Sensor_{i}");
dataList.Add(new SensorData { Id = i, Value = data });
}
// Batch write to database (more than 100x performance improvement)
CMS.BatchInsertToDatabase("data", dataList);
}
public class SensorData
{
public int Id { get; set; }
public double Value { get; set; }
}
Performance Comparison:
- Before optimization: 1000 database operations, takes about 10-30 seconds.
- After optimization: 1 batch operation, takes about 0.1-0.3 seconds.
- Performance improvement: more than 100x.
Value:
- Identify performance bottlenecks.
- Provide optimization solutions.
- Improve script execution efficiency.
5-Minute Quick Start
Step 1: Open the AI Script Assistant
In the script editor, click the "AI Assistant" icon on the toolbar, or right-click and select "AI-assisted writing".

Step 2: Describe Your Requirements
Enter your requirements in the dialog. You can:
- Generate a new script: Describe the functionality you need.
- Explain an existing script: Paste the code and request an explanation.
- Debug/optimize: Paste the problematic code and describe the issue.

Step 3: Wait for the AI to Generate
The AI will analyze the requirements and generate code or an explanation within 5-15 seconds.
Step 4: Test and Verify
- Copy the generated code to the script editor.
- Run and verify in a test environment.
- Fine-tune based on actual conditions.
Step 5: Deploy to Production
After successful testing, deploy to the production environment.
Prompting Tips (For Accurately Generating/Debugging Scripts)
Tip 1: Script Generation – "Condition-Action" Structure
Clearly describe trigger conditions and actions to perform.
Example 1 – Simple conditional trigger:
When the variable "Scan Completed" is true,
call the MES API endpoint "api/check_material" based on the scan result.
Example 2 – Complex condition combination:
Trigger an alarm when all the following conditions are met:
1. Temperature > 80 degrees
2. Pressure < 2 bar
3. Equipment status is "Running"
After triggering, execute:
1. Set alarm flag to true
2. Send email notification
3. Record alarm log to database
Example 3 – Data processing script:
Write a script that does the following:
1. Read the production log CSV file under D:\reports
2. Parse the file content
3. Insert the data into the "daily_log" table in the database
4. Back up the file to the D:\backup directory
5. Delete backup files older than 7 days
Note: This script can be configured via the scheduled tasks module to run automatically at 1 AM every day.
Tip 2: Specify Data Sources and Destinations
Indicate where the data comes from and where it should be written.
Example 1 – API Integration:
Write a script that does the following:
Data source:
- API URL: http://erp.company.com/api/orders
- Request method: GET
- Authentication: Bearer Token (obtained from variable "ERPToken")
Data processing:
- Parse the returned JSON array
- Filter orders with status "pending"
- Extract fields: orderNo, productCode, quantity
Data destination:
- Write to CMS variable: CurrentOrders (JSON string)
- Also write to database table "order_queue"
Example 2 – File processing:
Write a script to read an Excel file and import data:
File path: D:\import\products.xlsx
Worksheet: Sheet1
Columns to read: A (product code), B (product name), C (inventory quantity)
Processing logic:
- Skip the first row (header row)
- Validate product code format (must start with P followed by 6 digits)
- Inventory quantity must be greater than 0
Write destination:
- Database table "products"
- If product code already exists, update inventory quantity
- If it does not exist, insert a new record
Tip 3: Describe Complex Processes Step by Step
Break down multi-step requirements and generate them in stages before combining.
Example – Scan-to-inbound process:
Step 1: Get scan data
Write a script to listen for barcode scanner input:
- Monitored variable: ScanCode
- Trigger when the variable value changes
- Validate scan format: 20 digits
- Store valid scan in variable: ValidScanCode
Step 2: Call MES query
Use ValidScanCode to call the MES API and query material information:
- API: http://mes/api/getMaterial
- Parameters: {"barcode": "barcode"}
- Return: {"materialCode": "material code", "materialName": "material name", "batch": "batch"}
- Parse and store in variables: MaterialCode, MaterialName, Batch
Step 3: Write to database
Write material information to the inbound records table:
- Table name: inbound_records
- Fields: barcode, material_code, material_name, batch, inbound_time
- inbound_time uses current time
- After successful write, set variable InboundSuccess to true
Tip 4: Provide Context Information
Provide necessary background information to help the AI better understand the requirements.
Example:
Background: Our production line has 5 devices, each with 10 sensors.
Requirement: Write a script to calculate equipment health scores.
Calculation logic:
- Read the 10 sensor data values for each device (variable naming: Device1_Sensor1 to Device5_Sensor10)
- Each sensor has a normal range (stored in the configuration table sensor_config)
- If the sensor value is within the normal range, award 1 point; otherwise 0 points.
- Equipment health score = number of normal sensors / total sensors * 100%
- Write each device's health score to variables: Device1_Health to Device5_Health
- If the health score is below 80%, trigger an alarm.
Prompt Template Library
Template 1: API Data Retrieval
Write a script to fetch data from an API:
API information:
- URL: [API_URL]
- Method: [GET/POST]
- Authentication: [authentication method]
- Parameters: [parameter description]
Data processing:
- Parse the returned [JSON/XML]
- Extract fields: [field list]
- Data validation: [validation rules]
Write destination:
- CMS variables: [list of variable names]
- Database table: [table name] (optional)
Exception handling:
- If the API call fails, log the error
- Set timeout to [X] seconds
Template 2: Database Operations
Write a script to perform database operations:
Operation type: [query/insert/update/delete]
Database information:
- Table name: [table_name]
- Fields: [field1, field2, field3]
Operation logic:
- Trigger condition: [condition description]
- Data source: [CMS variable/API/file]
- Processing rules: [business rules]
Result handling:
- Success: [actions after success]
- Failure: [handling after failure]
Template 3: Data Processing Script
Write a data processing script:
Tasks:
1. [first step]
2. [second step]
3. [third step]
Data processing:
- Data source: [source description]
- Processing logic: [processing rules]
- Output destination: [destination description]
Exception handling:
- How to handle task failures
- Logging requirements
Note: After the script is written, trigger conditions (e.g., daily at X time / hourly / every X minutes) can be configured in the scheduled tasks module to execute this script automatically.
Template 4: Conditional Monitoring
Write a conditional monitoring script:
Monitored variables: [list of variables]
Trigger conditions:
- Condition 1: [condition description]
- Condition 2: [condition description]
- Logical relationship: [AND/OR]
Trigger actions:
1. [action 1]
2. [action 2]
3. [action 3]
Recovery condition:
- [recovery condition description]
Recovery actions:
- [actions after recovery]
Frequently Asked Questions
Q1: Can AI-generated scripts be used directly in production?
A: Not recommended. The correct workflow is:
- AI generates initial code.
- Run and verify in a test environment.
- Check that exception handling is complete.
- Performance testing.
- Deploy to production only after thorough testing.
Q2: What if the AI-generated code has syntax errors?
A:
- Check whether the requirement description is clear and complete.
- Redescribe the requirements, providing more context.
- Provide the error message to the AI and ask for a fix.
- Manually correct obvious syntax errors.
Q3: How can I make the AI generate code that better fits my project's standards?
A: When describing requirements, explicitly state:
- Naming conventions (e.g., use camelCase for variables naming).
- Comment requirements (e.g., add functional descriptions for each method).
- Exception handling requirements.
- Logging requirements.
Q4: How complex a script can the AI handle?
A: Recommendations:
- Simple scripts (under 50 lines): generate directly.
- Medium complexity (50-200 lines): generate module by module.
- Complex scripts (over 200 lines): generate step by step and combine gradually.
Q5: How can I optimize the performance of AI-generated code?
A:
- After generation, ask the AI: "How can I optimize the performance of this code?"
- The AI will analyze performance bottlenecks and provide optimization suggestions.
- Test the optimization effect in a real environment.
Best Practices
1. Be Specific in Requirement Descriptions
Each generation or modification consumes 10 credits, so describe clearly in one go to avoid repeated revisions.
❌ Bad description:
Write a script to read data.
✅ Good description:
Write a script to read 10 temperature sensor data points from the PLC (variable names: Temp1 to Temp10),
calculate the average, and trigger an alarm if the average exceeds 80 degrees.
2. Provide Complete Context
Include:
- Data source and format.
- Business rules and logic.
- How to handle exceptional situations.
- Performance requirements.
3. Handle Complex Logic Step by Step
For particularly complex scripts, you can generate them module by module before combining. However, note that each generation consumes 10 credits. Recommendations:
- Plan module division first.
- Describe each module clearly in one go.
- Finally, ask the AI to integrate all modules.
4. Make Good Use of the Code Explanation Feature
When encountering code you don't understand, ask the AI to explain it to deepen your understanding. Each explanation consumes 10 credits, so it is advisable to ask multiple questions in one go to improve efficiency.
5. Build a Script Template Library
Save commonly used and effective scripts as templates to improve team efficiency.
6. Test-Driven Development
After the script is generated, write test cases first to verify functional correctness.
7. Code Review
AI-generated code also requires manual review, paying special attention to:
- Security (SQL injection, XSS, etc.)
- Completeness of exception handling
- Whether performance meets requirements
Next Steps
- AI Model Assistant – After mastering script development, next learn about 3D equipment model generation to prepare model assets for pages and digital twin scenarios.
- AI Image Assistant – Continue learning about generating equipment images, background images, and schematic diagrams to supplement page visual assets.
- Usage Tips & Best Practices – After completing the main assistants, systematically study prompt writing, cross-assistant collaboration workflows, and team usage standards.